/**
 * Created by 小超 on 2014/8/20.
 */
var models = require("../models"),
    Good = models.Good,
    Order = models.Order,
    User = models.User,
    PayOff = models.PayOff,
    WCSession = models.WCSession,
    Message = models.Message,
    PubChatPay = models.PubChatPay;
var util_tool = require('../utils');
var util_wechat = require('../utils/wechatutil');
var async = require('async');
var _ = require('underscore');
var settings = require('../config');
module.exports = function (app) {
    app.get('/wcpay/payoff', function (req, res) {
        if (req.query.code) {
            new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                if (result) {
                    var openid = result.openid;
                    //根据openid查询用户
                    new User().findUserByOpenid(openid, function (err, user) {
                        if (err || !user) {
                            debug('get payoff info fail!', err);
                        } else {
                            //获取payoff信息
                            new util_tool().getpayoffinfo(openid, function (err, result) {
                                result.openid = openid;
                                res.render('payoff', {
                                    title: '结算页',
                                    result: result
                                })
                            })
                        }
                    })
                }
            });
        }
    })
    app.get('/wcpay/payoff/submit', function (req, res) {
        var openid = req.query.openid;
        new User().findUserByOpenid(openid, function (err, user) {
            if (user) {
                new util_tool().getpayoffinfo(openid, function (err, payoff) {
                    if (payoff.payoff_count > 0) {
                        payoff.payoff_date = new Date();
                        payoff.wcopenid = openid;
                        payoff.nickname = user.nickname;
                        payoff.savePayoff(function (err) {
                            if (err) {
                                debug('savePayoff fail', err);
                                res.render('error', {
                                    title: '出错啦',
                                    message: "系统繁忙请稍后再试...",
                                    err: err
                                })
                            } else {
                                res.render('payoff_commit', {
                                    title: '结算单提交成功',
                                    result: "结算单已经提交，请等待处理...",
                                    icon: "success"
                                })
                            }
                        })
                    } else {
                        res.render('payoff_commit', {
                            title: '结算单提交成功',
                            result: "您目前待结算的咨询次数为0，赶快去接诊吧...",
                            icon: "fail"
                        })
                    }
                })
            } else {
                res.render('error', {
                    title: '出错啦',
                    message: "没有找到相关用户。"
                })
            }
        })
    });

    app.get('/wcpay/payoff/exchange', function (req, res) {//兑换咨询次数
        var openid = req.query.openid;
        new User().findUserByOpenid(openid, function (err, user) {
            if (user) {
                new util_tool().getpayoffinfo(openid, function (err, payoff) {
                    if (payoff.payoff_count > 0) {
                        payoff.payoff_date = new Date();
                        payoff.wcopenid = openid;
                        payoff.nickname = user.nickname;
                        payoff.pay = 1;//设置为已付款
                        payoff.savePayoff(function (err) {
                            if (err) {
                                debug('savePayoff fail', err);
                                res.render('error', {
                                    title: '出错啦',
                                    message: "系统繁忙请稍后再试...",
                                    err: err
                                })
                            } else {
                                //更新用户咨询次数
                                new User().updateUserCountByOpneIdBuy(openid,payoff.payoff_count,function(err){
                                    if (err) {
                                        debug('savePayoff fail', err);
                                        res.render('error', {
                                            title: '出错啦',
                                            message: "系统繁忙请稍后再试...",
                                            err: err
                                        })
                                    }else{
                                        res.render('payoff_commit', {
                                            title: '兑换成功',
                                            result: "已兑换为咨询次数...",
                                            icon: "success"
                                        });
                                    }
                                });


                            }
                        })
                    } else {
                        res.render('payoff_commit', {
                            title: '结算单提交成功',
                            result: "您目前待结算的咨询次数为0，赶快去接诊吧...",
                            icon: "fail"
                        })
                    }
                })
            } else {
                res.render('error', {
                    title: '出错啦',
                    message: "没有找到相关用户。"
                })
            }
        })
    });

    app.get('/wcpay/payoff/his', function (req, res) {
        var openid = req.query.openid;
        if (openid) {
            new PayOff().findPayoff({wcopenid: openid}, function (err, result) {
                if (err) {
                    res.render('error', {
                        title: '出错啦',
                        message: "系统繁忙请稍后再试...",
                        err: err
                    })
                } else {
                    res.render('payoff_his', {
                        title: '结算历史页',
                        payoffs: result
                    });
                }
            })
        }
    });

    app.get('/wcpay/payoff/offline', function(req, res){
        var openid = req.query.openid;
        var message = {
            FromUserName:openid
        }
        if (openid) {
            new util_tool().signin('offline',message,function(msg){
                console.log(msg);
                if(msg=='ok'){
                    res.render('OK',{
                        title : '下线成功',
                        message : '下线成功！'
                    });
                }

            });

        }
    });
}
/**
 *
 * @param openid
 * @param callback
 *//*

function getpayoffinfo(openid, callback) {
    var message = new Message();
    var pubChatPay = new PubChatPay();
    async.waterfall([
        function (cb) {
            //查询结账单中该用户最后一次结账的时间
            new PayOff().findPayoff({wcopenid: openid}, function (err, result) {
                if (err) {
                    debug('findPayoff fail', err);
                    cb(err, '');
                } else {
                    if (result.length > 0) {//如果查询该用户结账单不为空,拿到
                        var payoff_date = result[0].payoff_date;
                        var total_count = 0;
                        _.each(result, function (payoff, index, list) {
                            total_count += payoff.payoff_count;
                        })
                        cb(null, payoff_date, total_count);
                    } else {
                        cb(null, null, null);
                    }
                }
            });
        },
        function (payoff_date, total_count, cb) {
            //查询本次结算单的session数量（续时的session根据续时次数增加本次结算次数）
            var condition = {
                stat: {$lt: 2},//0代表评价未统计;1代表评价已统计;2代表结算已统计
                receive_openid: openid,
                status: 2,
                chargeback:0,
                build_date: {
                    $gte: payoff_date
                }
            };
            if (!payoff_date) {
                delete condition['build_date'];
            }

            var condition1 = {
                "$or":[{"send_openid":openid},{"receive_openid":openid}],
                date: {
                    $gte: payoff_date
                }
            };
            new WCSession().findSessionCommon(condition, function (err, result) {//统计正常会话的次数
                pubChatPay.findPubChatPayById(condition1, function(err,docs){
                    var payoff_count = 0;
                    var payoff_info = new PayOff();
                    _.each(result, function (session, index, list) {
                        if (session.relet_count) {//获取用户续费次数默认0为1次
                            var rcount = session.relet_count + 1;
                            payoff_count += rcount;
                        } else {
                            payoff_count++;
                        }
                    });

                    _.each(docs, function (pubChatPay, index, list){
                        if(openid==pubChatPay.send_openid){//如果此openid等于咨询者id则统计为咨询者分成
                            payoff_count += pubChatPay.allocation;
                        }else{//统计为咨询师分成
                            payoff_count += pubChatPay.receiveAllocation;
                        }

                    });

                    payoff_info.payoff_count = parseFloat(payoff_count).toFixed(3);//所有会话总的结算次数
                    //payoff_info.income = payoff_count * settings.perincome;
                    payoff_info.income = parseFloat(payoff_count*settings.perincome).toFixed(3);
                    payoff_info.payoff_totalcount = parseFloat(payoff_count + total_count).toFixed(3);
                    cb(err, payoff_info);
                });

            });
        }
    ], function (err, result) {
        callback(err, result);
    });
}
*/
